package indi.zhifa.learn.jenkins.helloworld2.web.service.algorithm.datastructure;

import lombok.Data;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 没有找到pdfbox中目录中序遍历的接口，故自己实现
 */
@Data
public class PdfOutlineTreeNode {
    String title;
    Map<String,PdfOutlineTreeNode> children;
    PDOutlineItem beginBookMark;
    PDOutlineItem endBookMark;

    int beginPage;
    int endPage;

    public PdfOutlineTreeNode(){
        children = new HashMap<>();
        beginBookMark = null;
        endBookMark = null;
        title = "undefined";
    }

    public PdfOutlineTreeNode getChild(String pTitle) throws Exception {
        pTitle = pTitle.trim();
        PdfOutlineTreeNode child = children.get(pTitle);
        if(null == child){
            throw new Exception("节点 「"+title+"」 没有找到名为 「"+pTitle+"」　的子节点");
        }
        return child;
    }

    public void prepare(PDDocument pDoc) throws IOException {
        PDPageTree pages =pDoc.getPages();
        if(null != beginBookMark){
            PDPage beginPage = beginBookMark.findDestinationPage(pDoc);
            this.beginPage = pages.indexOf(beginPage);
        }
        if(null != endBookMark){
            PDPage endPage = endBookMark.findDestinationPage(pDoc);
            this.endPage = pages.indexOf(endPage);
        }
    }
}
